using B.S.XZYData.Api.Wrter.Application.Command.Plan;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Transactions;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Plan
{
    /// <summary>
    /// 批量删除生产计划处理器
    /// </summary>
    public class BatchDeletePlanHandler : IRequestHandler<BatchDeletePlanCommand, ApiResult<BatchDeletePlanResult>>
    {
        private readonly IBaseRepository<PlanModel> _planRepository;
        private readonly IBaseRepository<PlanItemModel> _planItemRepository;
        private readonly ILogger<BatchDeletePlanHandler> _logger;

        public BatchDeletePlanHandler(
            IBaseRepository<PlanModel> planRepository,
            IBaseRepository<PlanItemModel> planItemRepository,
            ILogger<BatchDeletePlanHandler> logger)
        {
            _planRepository = planRepository;
            _planItemRepository = planItemRepository;
            _logger = logger;
        }

        public async Task<ApiResult<BatchDeletePlanResult>> Handle(BatchDeletePlanCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new BatchDeletePlanResult
                {
                    TotalCount = request.PlanIds.Count
                };

                foreach (var planId in request.PlanIds)
                {
                    try
                    {
                        // 检查计划是否存在
                        var plan = _planRepository.GetAll()
                            .Where(x => x.Id == planId)
                            .ToList()
                            .FirstOrDefault();
                        if (plan == null)
                        {
                            result.FailedPlans.Add(new FailedPlanInfo
                            {
                                PlanId = planId,
                                Reason = "计划不存在"
                            });
                            continue;
                        }

                        // 检查是否有完成数量，有完成数量的不能删除
                        var planItems = _planItemRepository.GetAll()
                            .Where(x => x.PlanId == planId)
                            .ToList();
                        var hasCompleted = planItems.Any(x => x.DoneQuantity > 0);
                        
                        if (hasCompleted)
                        {
                            result.FailedPlans.Add(new FailedPlanInfo
                            {
                                PlanId = planId,
                                Reason = "该计划已有完成数量，不能删除"
                            });
                            continue;
                        }

                        // 开始删除 - 使用事务
                        using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                        
                        // 删除明细
                        await _planItemRepository.DeleteAsync(planId);
                        
                        // 删除主表
                        await _planRepository.DeleteAsync(planId);
                        
                        scope.Complete();
                        
                        result.SuccessPlanIds.Add(planId);
                        
                        _logger.LogInformation($"成功删除计划 {planId}，操作人：{request.OperateBy}");
                    }
                    catch (Exception ex)
                    {
                        result.FailedPlans.Add(new FailedPlanInfo
                        {
                            PlanId = planId,
                            Reason = $"删除失败：{ex.Message}"
                        });
                        
                        _logger.LogError(ex, $"删除计划 {planId} 失败，操作人：{request.OperateBy}");
                    }
                }

                result.SuccessCount = result.SuccessPlanIds.Count;
                result.FailedCount = result.FailedPlans.Count;

                return new ApiResult<BatchDeletePlanResult>
                {
                    Code = ApiEnum.Success,
                    Msg = $"批量删除完成，成功：{result.SuccessCount}，失败：{result.FailedCount}",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量删除生产计划失败，操作人：{request.OperateBy}");
                return new ApiResult<BatchDeletePlanResult>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"批量删除失败：{ex.Message}"
                };
            }
        }
    }
} 